﻿#region Copyright ©2008-2009, Technische Universitaet Muenchen
// ====================================================================================================
//
// Last Changed by       $Author: then $
// Last Changed Date     $LastChangedDate: 2009-03-19 13:58:26 +0100 (Thu, 19 Mar 2009) $
// Last Changed Revision $Rev: 42 $
//
// ====================================================================================================
#endregion

using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Media;
using Tum.CollabXT.DocxGen.Properties;

namespace Tum.CollabXT.DocxGen
{
    /// <summary>
    /// Interaction logic for DocxConfigPage.xaml
    /// </summary>
    public partial class DocxConfigPage : ToolProviderConfigPage
    {
        DocxGen ToolProvider;
        IConversionWorkflow ConversionWorkflow;


        public DocxConfigPage()
        {
            InitializeComponent();
        }

        public override void ReceiveProviderHandle(IToolProvider toolProvider)
        {
            ToolProvider = toolProvider as DocxGen;

            if (Directory.Exists(Settings.Default.LastTemplatePath))
                ToolProvider.TemplatePath = Settings.Default.LastTemplatePath;

            SetValues();
        }

        public override void ReceiveWorkflowHandle(IConversionWorkflow workflow)
        {
            ConversionWorkflow = workflow;

            UpdateWorkflowButtons();
        }

        private void UpdateWorkflowButtons()
        {
            if (ToolProvider != null)
            {
                ConversionWorkflow.UpdateButtonState(true, ToolProvider.OutputPath != null && ToolProvider.TemplatePath != null);
            }
        }

        public override bool PrevPageRequested()
        {
            ToolProvider.ProjectName = textBoxProjectName.Text;
            return base.PrevPageRequested();
        }

        public override bool NextPageRequested()
        {
            ToolProvider.ProjectName = textBoxProjectName.Text;
            return base.NextPageRequested();
        }

        private void SetValues()
        {
            //Output path
            if (ToolProvider.OutputPath == null)
                labelOutputPathValue.Content = Tum.CollabXT.DocxGen.Resources.Language.PathNotSet;
            else
            {
                labelOutputPathValue.Content = ToolProvider.OutputPath;
                labelOutputPathValue.Foreground = new SolidColorBrush(Color.FromRgb(0, 0, 0));
            }

            //Project name
            if (ToolProvider.ProjectName != null)
                textBoxProjectName.Text = ToolProvider.ProjectName;

            //Template path
            if (ToolProvider.TemplatePath == null)
                labelTemplatePathValue.Content = Tum.CollabXT.DocxGen.Resources.Language.PathNotSet;
            else
            {
                labelTemplatePathValue.Content = ToolProvider.TemplatePath;
                labelTemplatePathValue.Foreground = new SolidColorBrush(Color.FromRgb(0, 0, 0));
            }

            //Product list
            treeViewProducts.Items.Clear();

            //Insert disciplines
            Dictionary<string, int> disciplinePositionDictionary = new Dictionary<string, int>();
            foreach (IDiscipline curDiscipline in ToolProvider._ProcessProvider.Disciplines)
            {
                CheckableTreeItem tvi = new CheckableTreeItem(curDiscipline.Name);
                tvi.Tag = curDiscipline;
                disciplinePositionDictionary.Add(curDiscipline.Id, treeViewProducts.Items.Add(tvi));
            }

            //Insert products
            foreach (IProduct curProd in ToolProvider._ProcessProvider.Products)
            {
                CheckableTreeItem discTvi = treeViewProducts.Items.GetItemAt(disciplinePositionDictionary[curProd.DisciplineId]) as CheckableTreeItem;
                CheckableTreeItem newCti = new CheckableTreeItem(curProd.Name);
                newCti.Tag = curProd;
                newCti.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(TreeItemCheckBox_PropertyChanged);
                discTvi.Children.Add(newCti);
            }
            //------------

            foreach (CheckableTreeItem TreeRootElement in treeViewProducts.Items)
            {
                TreeRootElement.Initialize();

                foreach (CheckableTreeItem childCti in TreeRootElement.Children)
                    childCti.IsChecked = ToolProvider.ProductsToGenerated.Contains((childCti.Tag as IProduct).Id.ToLower());
            }

            //Button states
            UpdateWorkflowButtons();
        }


        /// <summary>
        /// Checked state has changed. Modify products to be generated accordingly.
        /// </summary>
        /// <param name="sender">Item of which the check state has changed.</param>
        /// <param name="e">Information about the changed parameter.</param>
        void TreeItemCheckBox_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            CheckableTreeItem senderItem = sender as CheckableTreeItem;
            if (senderItem.Tag is IProduct)
            {
                if (senderItem.IsChecked == true)
                    ToolProvider.ProductsToGenerated.Add((senderItem.Tag as IProduct).Id.ToLower());
                else
                    ToolProvider.ProductsToGenerated.Remove((senderItem.Tag as IProduct).Id.ToLower());

                ConversionWorkflow.InvalidateProcessing();
            }
        }

        private void buttonSetTemplatePath_Click(object sender, RoutedEventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.ShowNewFolderButton = false;

            if (Directory.Exists(Settings.Default.LastTemplatePath))
                fbd.SelectedPath = Settings.Default.LastTemplatePath;

            if (fbd.ShowDialog() == DialogResult.OK)
            {
                ToolProvider.TemplatePath = fbd.SelectedPath;
                ConversionWorkflow.InvalidateProcessing();
                SetValues();

                //Save path as 'last template path'
                Settings.Default.LastTemplatePath = ToolProvider.TemplatePath;
                Settings.Default.Save();
            }
        }

        private void buttonSetOutputPath_Click(object sender, RoutedEventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.ShowNewFolderButton = true;

            if (Directory.Exists(Settings.Default.LastOutputPath))
                fbd.SelectedPath = Settings.Default.LastOutputPath;

            if (fbd.ShowDialog() == DialogResult.OK)
            {
                ToolProvider.OutputPath = fbd.SelectedPath;
                ConversionWorkflow.InvalidateProcessing();
                SetValues();

                Settings.Default.LastOutputPath = fbd.SelectedPath;
                Settings.Default.Save();
            }
        }
    }
}
